// pages/registerinfo/registerinfo.js
import Dialog from '../../dist/dialog/dialog';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showMore: app.globalData.showMore,
    itemSex: "男",
    userInfo: {},
    activityId: null,
    activity: {},
    show: false,
    showSex: false,
    tranList: [],
    hasTrans: false,
    item: {}
  },
  onClose: function() {
    this.setData({
      show: false,
      showSex: false
    });
  },
  showSexSelect: function() {
    this.setData({
      showSex: true
    });
  },
  selectToItemSex: function(event) {
    var that = this;
    var data = event.currentTarget.dataset;
    that.toggle("item.sex", data.id);
    that.toggle("itemSex", data.id == 1 ? "男" : "女");
    that.toggle("showSex", false);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    app.getUserInfo(function(userInfo) {
      var item = {};
      item.activityId = options.id;
      item.uid = userInfo.id;
      item.name = userInfo.nickName;
      item.telphone = userInfo.telphone;
      item.sex = userInfo.sex;
      item.webchatNum = userInfo.weixinInfo;
      item.paymentAmount = "";
      item.remark = "";
      item.idcard = "";
      item.cusromize = "";
      item.enrollment = 1;
      item.avatarUrl = userInfo.avatarUrl;
      that.toggle("userInfo", userInfo);
      that.toggle("item", item);
      that.toggle("activityId", options.id);
      that.getActivity();
      that.toggle("itemSex", item.sex == 1 ? "男" : "女");
    });
  },
  getActivity: function() {
    var that = this;
    app.req({
      url: "wechat/activity/activityDetail",
      method: "post",
      data: {
        id: that.data.activityId
      },
      success: function(res) {
        if (res.code == 200) {
          that.setData({
            activity: res.data
          })
          that.toggle("item.paymentAmount", res.data.perCapita);
          that.getTransport();
        }else {
            wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
            })
        }
      }
    });
  },
  getTransport: function() {
    var that = this;
    app.req({
      url: 'wechat/dictionary/listBydictType',
      data: {
        dictType: 'ACT_TRANSPORT'
      },
      method: 'POST',
      success: function(res) {
        if (res.code == 200) {
          var list = res.data;
          var trans = that.data.activity.transportation;
          if (trans) {
            var dataList = [];
            var nowList = trans.split(",");
            for (var i = 0; i < list.length; i++) {
              var item = list[i];
              if (that.isInArray(nowList, item.dictValue + "")) {
                dataList.push(item);
              }
            }
            that.setData({
              tranList: dataList,
              hasTrans: true
            })
          }

        }else {
            wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
            })
        }
      }
    });

  },
  isInArray: function(arr, val) {　
    var testStr = ',' + arr.join(",") + ",";　　
    return testStr.indexOf("," + val + ",") != -1;
  },
  tapRadio: function(e) {
    var that = this;
    var list = that.data.tranList;
    for (var i = 0; i < list.length; i++) {
      list[i].isChoose = false;
    }
    that.setData({
      tranList: list
    })
    let name = e.currentTarget.dataset.name,
      ischoose = e.currentTarget.dataset.ischoose,
      value = e.currentTarget.dataset.value;
    this.toggle([name], !ischoose);
    this.toggle("item.transportation", !ischoose ? value : "");
  },
  toggle: function(type, val) {
    this.setData({
      [type]: val
    });
  },
  changeTextArea: function(event) {
    this.toggle(event.currentTarget.dataset.value, event.detail.value);
  },
  checkDataBeFilled: function() {
    var that = this;
    var activity = this.data.activity;
    var item = this.data.item;
    var flag = true;
    flag &= this.alert(activity.isName && !item.name.trim(), "请输入姓名");
    if (!flag) {
      return false;
    }
    flag &= this.alert(item.name.trim().length > 10, "姓名最多输入10个字符");
    if (!flag) {
      return false;
    }
    flag &= this.alert(activity.isSex && !item.sex, "请选择性别");
    if (!flag) {
      return false;
    }
    var phonePattern = /^((\d{3}-\d{8}|\d{4}-\d{7,8})|(1[3|5|7|8][0-9]{9}))$/;
    flag &= this.alert(activity.isTelphone && !item.telphone.trim(), "请输入手机号");
    if (!flag) {
      return false;
    }
    flag &= this.alert(activity.isTelphone && !phonePattern.test(item.telphone), "手机号填写有误");
    if (!flag) {
      return false;
    }
    flag &= this.alert(activity.isWechatNum && !item.webchatNum.trim(), "请输入微信号");
    if (!flag) {
      return false;
    }
    flag &= this.alert(activity.isIdcard && !item.idcard.trim(), "请输入身份证");
    if (!flag) {
      return false;
    }
    flag &= this.alert(activity.isIdcard && !this.isCardNo(item.idcard), "身份证填写错误");
    if (!flag) {
      return false;
    }
    flag &= this.alert(activity.isCusromize && !item.cusromize.trim(), "请输入" + activity.isCusromize);
    if (!flag) {
      return false;
    }
    flag &= this.alert(activity.enrollment && item.enrollment <= 0, "请输入报名人数");
    if (!flag) {
      return false;
    }
    flag &= this.alert(that.data.hasTrans && !item.transportation, "请选择出行方式");
    if (!flag) {
      return false;
    }
    return flag;
  },
  isCardNo: function(sId) {
    var iSum = 0;
    var aCity = {
      11: "北京",
      12: "天津",
      13: "河北",
      14: "山西",
      15: "内蒙古",
      21: "辽宁",
      22: "吉林",
      23: "黑龙江",
      31: "上海",
      32: "江苏",
      33: "浙江",
      34: "安徽",
      35: "福建",
      36: "江西",
      37: "山东",
      41: "河南",
      42: "湖北",
      43: "湖南",
      44: "广东",
      45: "广西",
      46: "海南",
      50: "重庆",
      51: "四川",
      52: "贵州",
      53: "云南",
      54: "西藏",
      61: "陕西",
      62: "甘肃",
      63: "青海",
      64: "宁夏",
      65: "新疆",
      71: "台湾",
      81: "香港",
      82: "澳门",
      91: "国外"
    };
    if (!/^\d{17}(\d|x)$/i.test(sId)) return false;
    sId = sId.replace(/x$/i, "a");
    if (aCity[parseInt(sId.substr(0, 2))] == null) return false;
    var sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2));
    var d = new Date(sBirthday.replace(/-/g, "/"));
    if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) return false;
    for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
    if (iSum % 11 != 1) return false;
    return true;
  },
  alert: function(flag, msg) {
    if (flag) {
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      })
    }
    return !flag;
  },
  confirmForm: function() {
    var that = this;
    var uid = that.data.userInfo.id;
    if (that.checkDataBeFilled()) {
      app.req({
        url: "wechat/act/roster/timeConflict",
        method: "post",
        data: {
          activityId: that.data.item.activityId,
          actStartTime: that.data.item.actStartTime,
          actEndTime: that.data.item.actEndTime
        },
        success: function (res) {
          if (res.code == 200) {
            if (that.data.activity.chooseConsume == 1) {
              //需要支付金额
              that.toggle("show", true);
            } else {
              //有人请客
              that.toggle("item.paymentAmount", "");
              that.goToRegisterPage();
            }
          } else {
            Dialog.confirm({
              message: res.msg,
              confirmButtonText: "是",
              cancelButtonText: "否"
            }).then(() => {
              if (that.data.activity.chooseConsume == 1) {
                //需要支付金额
                that.toggle("show", true);
              } else {
                //有人请客
                that.toggle("item.paymentAmount", "");
                that.goToRegisterPage();
              }
            }).catch(() => {
              // on cancel
            });
          }
        }
      });
    }
  },

  addToActivity: function() {
    var that = this;
    var data = that.data.item;
    app.req({
      url: "wechat/wxpay/pay",
      method: "post",
      showLoad: true,
      data: {
        activityId: data.activityId
      },
      success: function(res) {
        if (res.code == 200) {
          var paydata = res.data;
          wx.requestPayment({
            timeStamp: paydata.prepayDate.timeStamp,
            nonceStr: paydata.prepayDate.nonceStr,
            package: 'prepay_id=' + paydata.prepayDate.prepay_id,
            signType: 'MD5',
            paySign: paydata.prepayDate.paySign,
            success(res) {
              that.goToRegisterPage(paydata.outTradeNo);
            },
            fail(res) {
              console.log(res.errMsg)
            }
          })
        }else {
            wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
            })
        }
      }
    });
  },
  goToRegisterPage: function (paydata) {
    var that = this;
    var data = that.data.item;
    if (paydata){
      data.outTradeNo = paydata;
    }
    app.req({
      url: "wechat/act/participation/save",
      method: "post",
      data: data,
      showLoad: true,
      success: function(res) {
        if (res.code == 200) {
          // wx.navigateBack({
          //   delta: 1
          // })
          console.log("报名成功")
          wx.switchTab({
            url: '/pages/index/index'
          })
        } else {
          console.log("报名失败")
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },
})